package br.facet.dao;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.facet.pojo.Login;
import br.facet.utils.HibernateUtils;

public class LoginDAO {

	public void salvar(Login login) throws Exception {
		Session sessao = null;
		Transaction tx = null;

		try {
			sessao = HibernateUtils.getSession();
			tx = sessao.beginTransaction();
			sessao.save(login);
			tx.commit();

		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			if (sessao != null) {
				try {
					sessao.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}

	}
	
	public FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }

	public HttpSession getSession() {
        return (HttpSession) getFacesContext().getExternalContext().getSession(false);
    }
	
	
	public String autenticar(String login, String senha) throws Exception {
		Session sessao = null;
		String retorno = null;
		try {
			sessao = HibernateUtils.getSession();
			Query q = sessao
					.createSQLQuery(
							"select * from tbl_login where usuario = :login and senha = :senha")
					.setParameter("login", login).setParameter("senha", senha);

			if (q.uniqueResult() == (null)) {
				retorno = "erro";
			} else {
				retorno = "sucesso";
			}
		} catch (Exception e) {
			retorno = "erro";
		} finally {
			if (sessao != null) {
				try {
					sessao.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		return retorno;

	}
}
